package com.musiclibrary.scraper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.musiclibrary.common.JsoupUtils;
import com.musiclibrary.persistence.MusicCategory;

public class MarathiScraper implements MusicScraper{

	private WebPage<Map<String, String>> webPage;

	public MarathiScraper(){
		
	}
	
	public MarathiScraper(WebPage<Map<String,String>> webPage){
		this.webPage=webPage;
		initWebPage(webPage);
	}
	
	public WebPage<Map<String, String>> getWebPage() {
		return webPage;
	}

	public void setWebPage(WebPage<Map<String, String>> webPage) {
		this.webPage = webPage;
		initWebPage(webPage);
	}

	private void initWebPage(final WebPage<Map<String, String>> webPage) {
		webPage.setFormHandler(new FormHandler<Map<String, String>>() {

			public void updateForm(Map<String, String> data) {
				webPage.getHtmlForm().setFromParameters(data);
			}
		});
	}

	public List<MusicCategory> loadPage() {
		List<MusicCategory> musicCategories=null;
		try{
			if(getWebPage()!=null){
				//read web page from Site
				Document document = new JsoupUtils().loadPage(getWebPage());
				
				//parse Document
				if(document!=null){
					musicCategories=parseDocument(document);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return musicCategories;
	}

	private List<MusicCategory> parseDocument(Document document){
		List<MusicCategory> musicCategories=null;
		try{
			MarathiMusicCategoryParser musicCategoryParser=new MarathiMusicCategoryParser();
			Elements categoryElements = document.select("body div#mainDiv div#cateogry div.catList div.catRow");
			if(categoryElements!=null && categoryElements.size()>0){
				musicCategories=new ArrayList<MusicCategory>();
				for(Element element:categoryElements){
					MusicCategory musicCategory = musicCategoryParser.parseMusicCategory(element, webPage);
					musicCategories.add(musicCategory);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return musicCategories;
	}
}
